package com.itany.controller;


import com.github.pagehelper.PageInfo;
import com.itany.constant.ResponseConstant;
import com.itany.exception.RequestParamsException;
import com.itany.pojo.User;
import com.itany.service.UserService;
import com.itany.vo.ActionResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {
	
	@Autowired
	UserService userService;

	/**
	 * 查找所有用户
	 * @param page 页码数
	 * @param rows 每页数据条数
	 * @return 分页用户信息
	 */
	@RequestMapping("/findAll")
	@ResponseBody
	public Map<String,Object> findAll(@RequestParam(defaultValue="1")Integer page,
									  @RequestParam(defaultValue="10")Integer rows,
									  String keyword,String flag){
		Map<String,Object> map = new HashMap<>();
		PageInfo<User> info = null;
		try {
			info = userService.findUserAll(page, rows,keyword,flag);
		} catch (RequestParamsException e) {
			e.printStackTrace();
		}
		map.put("total", info.getTotal());
		map.put("rows", info.getList());
		return map;
	}

	/**
	 * 修改用户信息
	 * @param id 前端数据 -id
	 * @param name 前端数据- 用户名
	 * @param phone 前端数据 - 号码
	 * @param email  前端数据 - 邮箱
	 * @param interest 前端数据 - 爱好
	 * @return 响应信息
	 */
	@RequestMapping("/modifyUser")
	@ResponseBody
	public ActionResult modifyUser(String id, String name, String phone, String email, String interest){
		ActionResult result = new ActionResult();
		try {
			userService.modifyUser(id,name,phone,email,interest);
			result.setMsg("修改成功");
			result.setStatus(ResponseConstant.RESPONSE_SUCCESS);
		} catch (RequestParamsException e) {
			result.setMsg(e.getMessage());
			result.setStatus(ResponseConstant.REQUEST_PARAMETER_ERROR);
		}catch (Exception e){
			result.setMsg("服务器内部异常");
			result.setStatus(ResponseConstant.SERVER_ERROR);
		}
		return result;
	}

	/**
	 * 设置指定用户状态
	 * @param id 用户id
	 * @param status 该用户待修改的状态
	 * @return 响应数据
	 */
	@RequestMapping("/status/{status}")
	@ResponseBody
	public ActionResult enable(String id, @PathVariable("status") Integer status){
		ActionResult result = new ActionResult();
		try {
			userService.modifyStatus(id,status);
			result.setStatus(ResponseConstant.RESPONSE_SUCCESS);
		} catch (RequestParamsException e) {
			e.printStackTrace();
			result.setMsg(e.getMessage());
			result.setStatus(ResponseConstant.REQUEST_PARAMETER_ERROR);
		}catch (Exception e){
			e.printStackTrace();
			result.setMsg("服务器内部异常");
			result.setStatus(ResponseConstant.SERVER_ERROR);
		}
		return result;
	}




}
